package com.example.admin.brainwave.ui.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.IBinder;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.admin.brainwave.BluetoothServers;
import com.example.admin.brainwave.R;
import com.example.admin.brainwave.base.BaseActivity;
import com.example.admin.brainwave.utils.AudioUtils;
import com.example.admin.brainwave.utils.Const;
import com.example.admin.brainwave.utils.ProgressDialogManager;
import com.example.admin.brainwave.utils.SPHelper;
import com.example.admin.brainwave.utils.ToastUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

public class BrainCollectionActivity extends BaseActivity implements BluetoothServers.OnServiceGetDataListener {


    @BindView(R.id.chart1)
    LineChart mChart1;
    @BindView(R.id.chart2)
    LineChart mChart2;
    @BindView(R.id.chart3)
    LineChart mChart3;
    @BindView(R.id.iv_top_back)
    ImageView ivTopBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.iv_top_connect)
    ImageView ivTopConnect;
    int flag = 0;
    private Intent serviceIntent;
    private BluetoothServers mService;
    private CommandReceiver cmdReceiver;
    BluetoothAdapter mBluetoothAdapter;
    private ArrayList<double[]> buff;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_brain_collection;
    }


    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(final ComponentName className, final IBinder rawBinder) {
            mService = ((BluetoothServers.ServiceBinder) rawBinder).getService();
            mService.setOnServiceGetDataListener(BrainCollectionActivity.this);
            buff = new ArrayList<>();
            if (flag == 1) {
                mService.setFirst(true);
            } else if (flag == 2) {
                mService.setFirst(false);
            }
            showDialog();
        }

        @Override
        public void onServiceDisconnected(final ComponentName classname) {
            mService = null;
        }
    };


    @Override
    public void onDataChanged(double[] data) {
        buff.add(data);
        if (buff.size() == 100) {
            List<double[]> newlist = new ArrayList<>();
            newlist.addAll(buff);
            buff.clear();
            for (int i = 0; i < newlist.size(); i++) {
                addEntry((float) newlist.get(i)[0], mChart1);
                addEntry((float) newlist.get(i)[1], mChart2);
                addEntry((float) newlist.get(i)[2], mChart3);
            }
        }

    }

    @Override
    protected void initView() {

        tvTopTitle.setText(getResources().getString(R.string.brain_collection));
        ivTopConnect.setVisibility(View.VISIBLE);

        setmChart(mChart1);
        setX(mChart1);
        setY(mChart1);
        mChart1.setData(new LineData());
        mChart1.invalidate();

        setmChart(mChart2);
        setX(mChart2);
        setY(mChart2);
        mChart2.setData(new LineData());
        mChart2.invalidate();

        setmChart(mChart3);
        setX(mChart3);
        setY(mChart3);
        mChart3.setData(new LineData());
        mChart3.invalidate();

        flag = getIntent().getIntExtra("flag", 0);
    }

    @Override
    protected void addListener() {
        ivTopBack.setOnClickListener(view -> finish());
        ivTopConnect.setOnClickListener(view -> startActivity(new Intent(BrainCollectionActivity.this, BluetoothActivity.class)));
    }

    @Override
    protected void initData() {
        cmdReceiver = new CommandReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Const.BLUETOOTH_CONNECT);
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(cmdReceiver, filter);
        serviceIntent = new Intent(this, BluetoothServers.class);
        bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }


    private void showDialog() {
        if (mBluetoothAdapter == null) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        ArrayList<String> name = new ArrayList<>();
        final ArrayList<BluetoothDevice> mac = new ArrayList<>();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                name.add(device.getName().toString());
                mac.add(device);
            }
        } else {
            Toast.makeText(this, "暂无已配对设备", Toast.LENGTH_SHORT).show();
            finish();
        }
        String device_name[] = new String[mac.size()];
        for (int i = 0; i < name.size(); i++) {
            device_name[i] = name.get(i);
        }
        if (device_name.length > 0) {
            if (flag == 1) {
                AlertDialog.Builder alertdialog = new AlertDialog.Builder(this);
                alertdialog.setTitle("选择已配对的设备一").setItems(device_name, (dialog, which) -> {
                    mService.bluetoothConnect(mac.get(which));
                    SPHelper.getInstance(BrainCollectionActivity.this).putInt("macPos", which);
                    dialog.dismiss();
                    ProgressDialogManager.showDialog(BrainCollectionActivity.this);
                });
                alertdialog.setCancelable(false);
                alertdialog.create();
                alertdialog.show();
            } else if (flag == 2) {
                int pos = SPHelper.getInstance(this).getInt("macPos", 0);
                mService.bluetoothConnect(mac.get(pos));
                ProgressDialogManager.showDialog(this);
            }
        }
    }


    private void setmChart(LineChart lineChart) {
        lineChart.setDrawGridBackground(false);
        lineChart.setTouchEnabled(true);
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        lineChart.setPinchZoom(false);
        lineChart.getLegend().setEnabled(false);
        Description d = new Description();
        d.setText("");
        lineChart.setDescription(d);
        //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
        lineChart.zoom(2f, 1f, 0, 0);
        lineChart.resetTracking();
    }


    private void setX(LineChart lineChart) {
        lineChart.getXAxis().setAxisLineColor(Color.parseColor("#B3B5B8"));
        lineChart.getXAxis().setTextColor(Color.parseColor("#B3B5B8"));
        lineChart.getXAxis().setDrawAxisLine(true);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        lineChart.getXAxis().setGranularity(1f);
        lineChart.getXAxis().setAxisLineWidth(1f);
        lineChart.getXAxis().setGridColor(Color.parseColor("#E9EEF2"));
    }

    private void setY(LineChart lineChart) {
        lineChart.getAxisLeft().setAxisLineColor(Color.parseColor("#B3B5B8"));
        lineChart.getAxisLeft().setTextColor(Color.parseColor("#B3B5B8"));
        lineChart.getAxisLeft().setDrawGridLines(true);
        lineChart.getAxisLeft().setGranularity(1f);
        lineChart.getAxisLeft().setAxisLineWidth(1f);
        lineChart.getAxisLeft().setEnabled(true);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getAxisLeft().setGridColor(Color.parseColor("#E9EEF2"));
    }


    public void addEntry(float yValues, LineChart lineChart) {
        LineData lineData = lineChart.getData();
        if (lineData != null) {
            int indexLast = getLastDataSetIndex(lineData);
            LineDataSet lastSet = (LineDataSet) lineData.getDataSetByIndex(indexLast);
            if (lastSet == null) {
                lastSet = createLineDataSet();
                lineData.addDataSet(lastSet);
            }
            int count = lastSet.getEntryCount();
            lineData.addEntry(new Entry(count, yValues), indexLast);
            lineChart.notifyDataSetChanged();
            lineChart.moveViewTo(count, yValues, YAxis.AxisDependency.LEFT);
        }
    }

    private int getLastDataSetIndex(LineData lineData) {
        int dataSetCount = lineData.getDataSetCount();
        return dataSetCount > 0 ? (dataSetCount - 1) : 0;
    }

    private LineDataSet createLineDataSet() {
        LineDataSet dataSet = new LineDataSet(null, "DataSet");
        dataSet.setColor(Color.parseColor("#29A1D7"));
        dataSet.setLineWidth(1f);
        dataSet.setDrawValues(false);
        dataSet.setDrawCircles(false);
        dataSet.setMode(LineDataSet.Mode.LINEAR);
        dataSet.setDrawFilled(false);
        return dataSet;
    }


    private class CommandReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0);
            if (action.equals(Const.BLUETOOTH_CONNECT)) {
                String state = intent.getStringExtra("state");
                if ("0".equals(state)) {
                    ProgressDialogManager.dismissProgressDialog();
                    mService.writeSerial("uaisb");
                    if (flag == 1) {
                        AudioUtils.playSound(BrainCollectionActivity.this, R.raw.audio0, mp1 -> {
                        });
                        timer.schedule(timerTask, 90000);
                    } else if (flag == 2) {
                        AudioUtils.playSound(BrainCollectionActivity.this, R.raw.audio72, mp -> {
                            Intent intent2 = new Intent(BrainCollectionActivity.this, BrainCollectionHomeActivity.class);
                            intent2.putExtra("flag", 3);
                            startActivity(intent2);
                            stopDevices();
                            finish();
                        });
                    }
                } else {
                    ToastUtil.showShort(BrainCollectionActivity.this, "连接设备失败");
                    showDialog();
                }
            }
            if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED) && bluetoothState == BluetoothAdapter.STATE_DISCONNECTED) {
                ToastUtil.showShort(BrainCollectionActivity.this, "设备断开连接");
                stopDevices();
                finish();
            }
        }
    }


    Timer timer = new Timer();
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            Intent intent1 = new Intent(BrainCollectionActivity.this, BrainCollectionHomeActivity.class);
            intent1.putExtra("flag", 2);
            startActivity(intent1);
            stopDevices();
            finish();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        unregisterReceiver(cmdReceiver);
        unbindService(mServiceConnection);
    }

    @Override
    protected void onPause() {
        AudioUtils.pause();
        super.onPause();
    }


    private void stopDevices() {
        if (mService != null) {
            mService.closeAll();
        }
    }

}
